package org.apak.frontend;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apak.control.DeviceForm;
import org.apak.db.RepairServiceDAO;
import org.apak.log.FileLogger;
import org.apak.model.Device;
import org.apak.model.DeviceType;
import org.apak.model.LoggedSubject;

/**
 * Servlet implementation class DeviceSearchServlet
 */
public class DeviceSearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private RepairServiceDAO dao = new RepairServiceDAO();
	private HttpSession session;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
		LoggedSubject loggedSubject = (LoggedSubject) session.getAttribute("loggedSubject");
		if(loggedSubject == null || loggedSubject.isCustomer()) {
			RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
			dispatcher.forward(request, response);
		} else {
			DeviceType[] deviceTypeArray = dao.getDeviceTypeList();
			request.setAttribute("deviceTypeArray", deviceTypeArray);
			FileLogger.logMessage("Forwarded to deviceSearch.jsp from DeviceSearchServlet.doGet().");
			RequestDispatcher dispatcher = request.getRequestDispatcher("deviceSearch.jsp");
			dispatcher.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DeviceType[] deviceTypeArray = dao.getDeviceTypeList();
		DeviceForm deviceForm = new DeviceForm(request.getParameter("name"),
				request.getParameter("reg_no"), request.getParameter("description"),
				request.getParameter("model"), request.getParameter("manufacturer"), request.getParameter("device_type"), request.getParameter("customerName"));
		Device[] deviceArray = dao.searchDevice(deviceForm);
		request.setAttribute("deviceTypeArray", deviceTypeArray);
		request.setAttribute("deviceForm", deviceForm);
		request.setAttribute("deviceArray", deviceArray);
		FileLogger.logMessage("Forwarded to deviceSearch.jsp from DeviceSearchServlet.doPost().");
		RequestDispatcher dispatcher = request.getRequestDispatcher("deviceSearch.jsp");
		dispatcher.forward(request, response);
	}

}
